package com.hmbe.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmbe.dto.Result;
import com.hmbe.entity.ShopType;
import com.hmbe.mapper.ShopTypeMapper;
import com.hmbe.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.hmbe.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //将商铺类型信息查询出来并缓存,以提高页面加载速度
        //1.查询缓存中是否有数据
        String shopTypeStr = stringRedisTemplate.opsForValue().get(CACHE_SHOP_TYPE_KEY);
        //2.如果缓存中有数据,则直接返回
        if (null != shopTypeStr) {
            //将json字符串转换为List<ShopType>
            List<ShopType> shopTypeList = JSONUtil.toList(shopTypeStr, ShopType.class);
            return Result.ok(shopTypeList);
        }
        //3.如果缓存中没有数据,则查询数据库
        List<ShopType> shopTypeList = query().orderByDesc("sort").list();
        //4.将查询到的数据放入缓存,并返回
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_TYPE_KEY, JSONUtil.toJsonStr(shopTypeList));
        //5.如果查询不到数据,则返回null
        if (shopTypeList == null || shopTypeList.isEmpty()) {
            return Result.fail("商铺信息不见了");
        }
        return Result.ok(shopTypeList);
    }
}
